/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.v1.client.http.handlers;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.yobidrive.y3.http.HttpResponseHandler;
import com.yobidrive.y3.utils.XMLUtils;
import com.yobidrive.y3.v1.model.Access;
import com.yobidrive.y3.v1.model.Action;
import com.yobidrive.y3.v1.model.GetDriveListResult;
import com.yobidrive.y3.v1.model.GetNodeDetailsResult;
import com.yobidrive.y3.v1.model.HistoryEntry;
import com.yobidrive.y3.v1.model.Member;
import com.yobidrive.y3.v1.model.RequestChallengeResult;
import com.yobidrive.y3.v1.model.RequestTokenResult;


public class GetNodeDetailsResponseHandler extends HttpResponseHandler<GetNodeDetailsResult>{

	static private final Logger logger = Logger.getLogger(GetNodeDetailsResponseHandler.class);
	
	@Override
	public GetNodeDetailsResult handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		
		//Call super to handle every error messages
		super.handleResponse(response);
		
		GetNodeDetailsResult result = new GetNodeDetailsResult();
		
		//Parse XML response
		HttpEntity entity = response.getEntity();
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(entity.getContent());
			Element rootElement = doc.getDocumentElement(); 
			
			result.uid 			= XMLUtils.getChildText(rootElement, "uid");
			result.name 		= XMLUtils.getChildText(rootElement, "name");
			result.type			= XMLUtils.getChildText(rootElement, "type");
			result.description 	= XMLUtils.getChildText(rootElement, "description");
			result.keywords 	= XMLUtils.getChildText(rootElement, "keywords");
			
			result.size 		= XMLUtils.stringToLong(XMLUtils.getChildText(rootElement, "size"),-1);
			result.version 		= XMLUtils.getChildText(rootElement, "version");
			result.lastModified	= XMLUtils.getChildText(rootElement, "lastmodified");
			result.lastModifier = XMLUtils.getChildText(rootElement, "lastmodifier");
			result.createdBy	= XMLUtils.getChildText(rootElement, "createdby");
			result.creationDate = XMLUtils.getChildText(rootElement, "creationdate");
			
			//Visibility info
			result.isVisibleActions = XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "isvisibleactions"), true);
			result.isVisibleHistory = XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "isvisiblehistory"), true);
			result.isVisibleReaders = XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "isvisiblereaders"), true);
			result.isVisibleWriters = XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "isvisiblewriters"), true);
			result.isVisibleOwners  = XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "isvisibleowners"), true);
			result.isVisibleAccesses= XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "isvisibleaccesses"), true);
			
			result.isPayer				= XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "ispayer"), false);
			result.enableAuditTrail		= XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "enableaudittrail"), true);
			result.enableManualPublish	= XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "enablemanualpublish"), true);
			result.enableReaders		= XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "enablereaders"), true);
			result.enableWriters		= XMLUtils.stringToBoolean(XMLUtils.getChildText(rootElement, "enablewriters"), true);
			
			Element teamElement = XMLUtils.getChildByName(rootElement, "writers");
			if ( teamElement != null  ) {
				NodeList members = teamElement.getElementsByTagName("member");
				Member[] team = new Member[members.getLength()];
				for ( int i=0; i<members.getLength(); i++) {
					team[i] = new Member();
					team[i].email = XMLUtils.getChildText(members.item(i),"email");
					team[i].local = XMLUtils.getChildText(members.item(i),"local");
					team[i].status= XMLUtils.getChildText(members.item(i),"status");
				}
				result.writers = team;
			}
			
			Element readersElement = XMLUtils.getChildByName(rootElement, "readers");
			if ( readersElement != null  ) {
				NodeList members = readersElement.getElementsByTagName("member");
				Member[] readers = new Member[members.getLength()];
				for ( int i=0; i<members.getLength(); i++) {
					readers[i] = new Member();
					readers[i].email = XMLUtils.getChildText(members.item(i),"email");
					readers[i].local = XMLUtils.getChildText(members.item(i),"local");
					readers[i].status= XMLUtils.getChildText(members.item(i),"status");
				}
				result.readers = readers;
			}
			
			Element ownersElement = XMLUtils.getChildByName(rootElement, "owners");
			if ( ownersElement != null  ) {
				NodeList members = ownersElement.getElementsByTagName("member");
				Member[] owners = new Member[members.getLength()];
				for ( int i=0; i<members.getLength(); i++) {
					owners[i] = new Member();
					owners[i].email = XMLUtils.getChildText(members.item(i),"email");
					owners[i].local = XMLUtils.getChildText(members.item(i),"local");
					owners[i].status= XMLUtils.getChildText(members.item(i),"status");
				}
				result.owners = owners;
			}

			Element historyElement = XMLUtils.getChildByName(rootElement, "history");
			if ( historyElement != null  ) {
				NodeList historyEntries = historyElement.getElementsByTagName("historyentry");
				HistoryEntry[] history = new HistoryEntry[historyEntries.getLength()];
				for ( int i=0; i<historyEntries.getLength(); i++) {
					history[i] = new HistoryEntry();
					history[i].issuer = XMLUtils.getChildText(historyEntries.item(i),"issuer");
					history[i].timestamp = XMLUtils.getChildText(historyEntries.item(i),"timestamp");
					history[i].version = XMLUtils.getChildText(historyEntries.item(i),"version");
					history[i].actionId = XMLUtils.getChildText(historyEntries.item(i),"actionid");
					history[i].details = XMLUtils.getChildText(historyEntries.item(i),"details");
				}
				result.history= history;
			}
			
			Element actionsElement = XMLUtils.getChildByName(rootElement, "actions");
			if ( actionsElement != null  ) {
				NodeList actions = actionsElement.getElementsByTagName("action");
				Action[] action = new Action[actions.getLength()];
				for ( int i=0; i<actions.getLength(); i++) {
					action[i] = new Action();
					action[i].action = XMLUtils.getChildText(actions.item(i),"action");
				}
				result.actions= action;
			}
			
			Element accessesElement = XMLUtils.getChildByName(rootElement, "accesses");
			if ( accessesElement != null  ) {
				NodeList accesses = accessesElement.getElementsByTagName("access");
				Access[] access = new Access[accesses.getLength()];
				for ( int i=0; i<accesses.getLength(); i++) {
					access[i] = new Access();
					access[i].timestamp = XMLUtils.getChildText(accesses.item(i),"timestamp");
					access[i].user		= XMLUtils.getChildText(accesses.item(i),"user");
					access[i].version	= XMLUtils.getChildText(accesses.item(i),"version");
				}
				result.accesses= access;
			}
			
		} catch (Exception ex) {
			logger.error("Error handling response",ex);
			return null;
		}
		
		return result;
	}

	
	
}
